//
//  MyURLCache.m
//  QLadder
//
//  Created by xiongguobing on 2019/7/29.
//  Copyright © 2019 qding. All rights reserved.
//

#import "MyURLCache.h"
#import "IPToolManager.h"

@interface MyURLCache ()

@property (nonatomic, strong) NSString * ip;

@end

@implementation MyURLCache

- (instancetype)init
{
    self = [super init];
    if (self) {
        kWeakSelf(self);
        [NetworkManager.sharedManager getIPAndCity:^(NSString * _Nullable ip, NSString * _Nonnull currentCity) {
            weakself.ip = ip;
        }];
    }
    return self;
}

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSLog(@"request url is %@", request.URL.absoluteString);
    NSData * data = request.HTTPBody;
    if (data) {
        NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"data is %@", str);
    }
    
    NSURL * url = request.URL;
    if ([self isBeginRequestWithUrl:url]) {
        [self uploadLogsWithUrl:url];
    }
    
    return [super cachedResponseForRequest:request];
}

- (BOOL)isBeginRequestWithUrl:(NSURL *)url
{
    __block BOOL isRequest = YES;
    NSString * urlStr = url.absoluteString;
    
    //没有连接VPN，不发送
    if (!kNetworkUtil.isVPNConnected) {
        isRequest = NO;
        return isRequest;
    }
    
    //包含本应用内的请求，不发送。
    if ([url.absoluteString containsString:BaseURL]) {
        isRequest = NO;
        return isRequest;
    }
    
    //包含以下资源文件的请求，不发送
    NSArray * clipsArr = @[@".css", @".js", @".jpg", @".png", @".jpeg", @".gif", @".woff", @".woff2", @".eot", @".otf", @".fon", @".font", @".ttf", @".ttc", ];
    [clipsArr enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([urlStr hasSuffix:obj]) {
            isRequest = NO;
            *stop = YES;
        }
        NSString * str = [obj stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSString * originStr = [urlStr componentsSeparatedByString:@"?"].firstObject;
        if ([originStr hasSuffix:obj] || [originStr hasSuffix:str] || [originStr hasSuffix:str.uppercaseString]) {
            isRequest = NO;
            *stop = YES;
        }
    }];
    
    return isRequest;
}

- (void)uploadLogsWithUrl:(NSURL *)url
{
    NSString * destPort = @"-1";
    NSString * destIp = @"";
    destIp = url.host;
    destPort = url.port.stringValue;
    if (!destPort.length) {
        if ([[url.scheme lowercaseString] isEqualToString:@"https"]) {
            destPort = @"443";
        }else if ([[url.scheme lowercaseString] isEqualToString:@"http"]){
            destPort = @"80";
        }
    }
    
    //流量服务器IP port
    NSString * inIp = @"";
    NSString * inPort = @"";
    NSArray * arr = [kUserDefaults objectForKey:@"KUserDefaultsProxys"];
    if (arr) {
        NSDictionary * dic = arr.firstObject;
        inIp = [NSString stringWithFormat:@"%@", dic[@"host"]];
        inPort = dic[@"port"];
    }
    
    //用户名
    NSString * userName = [kUserDefaults objectForKey:kUserAccount];
    
    //用户IP
    IPToolManager *ipManager = [IPToolManager sharedManager];
    NSString * srcIp = [ipManager currentIpAddress];
    NSString * srcPort = [NSString stringWithFormat:@"%ld", (long)[kUserDefaults integerForKey:@"randomPort"]];
    
    NSString * accessTime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    NSDictionary * dic = @{@"accessTime" : accessTime, @"destIp" : destIp, @"destPort" : destPort, @"inIp" : inIp, @"inPort" : inPort, @"loginName" : userName, @"srcIp" : srcIp, @"srcPort" : srcPort};
    [kNetworkUtil postWithModuleURLStr:userAccessLog parameters:dic success:^(id response) {
    } failure:nil isShowError:NO];

}

@end
